<template>
  <div v-if="Object.keys(curGroup).length" :class="pageWithSidebar">
    <groups-sidebar />
<!--    <header-reminder />-->
    <router-view />
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import HeaderReminder from '@/components/announcement/HeaderReminder';
import GroupsSidebar from './groups-sidebar';
import { formatGroup } from '../format';

export default {
  name: 'GroupsShow', // 群组展示页面
  components: { GroupsSidebar, HeaderReminder },
  computed: {
    ...mapState({ curGroup: 'currentGroup' }),
    ...mapState(['sidebarCollapsed', 'invisibleSidebar']),
    ...mapGetters(['isWebAdmin', 'isGroupOwner', 'isGroupAdmin']),
    groupId() { return this.$route.params.groupId; },
    // 有侧边栏的页面调用这个方法生成样式
    pageWithSidebar() {
      let className = 'page-with-sidebar';
      if (window.innerWidth < 1200 || this.sidebarCollapsed) className += ' sidebar-collapsed';
      if (window.innerWidth < 768 || this.invisibleSidebar) className += ' invisible-sidebar';
      return className;
    },
  },
  created() { this.loadGroup(); },
  destroyed() { this.removeCurGroup(); },
  methods: {
    ...mapActions({
      setCurGroup: 'setCurrentGroup',
      removeCurGroup: 'removeCurrentGroup',
    }),
    loadGroup() {
      this.$api.groups.show({ groupId: this.groupId })
        .then((res) => {
          // setTimeout(() => this.setCurGroup(formatGroup(res.data)), 2000);
          this.setCurGroup(formatGroup(res.data));
          this.accessPermissions();
        })
        .catch((err) => { if (err) this.goBack(); });
    },
    // 检查访问权限
    accessPermissions() {
      const isAdmin = this.isWebAdmin || this.isGroupOwner || this.isGroupAdmin;
      if (this.$route.meta.requireAdmin && !isAdmin) {
        this.$message.error('您没有权限访问这个页面');
        this.goBack();
      }
    },
    reloadGroup() {
      this.removeCurGroup();
      this.loadGroup();
    },
  },
  watch: {
    groupId() {
      this.removeCurGroup();
      this.loadGroup();
    },
    $route() { this.accessPermissions(); },
  },
};
</script>

<style></style>
